<?php

namespace co2_OS\apps\sdk\dev\v0_0_0;

use co2_OS as kernel;
use co2\dev\v0_0_0 as api;

class app

{
  protected
    $pkg,
    $version='0.0.0',
    $channel='dev'
    ;
    
  public function __construct
  (
    $pkg,
    \stdClass $options=null
  )
  {
    $this->pkg=$pkg;
    $Version=preg_replace('/\./','_',$this->version);
    $distrib=$this->channel=='dev'?'branches':'trunk';
    $dir="storage";
    $api_version=kernel\sysvar::get('api');
    $api_channel=kernel\sysvar::get('api_channel');
    $nutshell='Another kick-ass co2 app';
    
    if(is_object ($options))
    
    {
      if(isset($options->nutshell) && is_string($options->nutshell))
      $nutshell=$options->nutshell;
    }
    
    $aptitude=kernel\aptitude::get(kernel\aptitude::TYPE_APP,$pkg);
    
    if(count($aptitude))
    throw new api\Exception('There is already an application called '.$pkg);
    
    $base=kernel\sysvar::get('apps')."/$pkg";
    
    new api\bash\mkdir($base,array('p'));
    
    new api\bash\mkdir("$base/$this->channel");
    new api\bash\mkdir("$base/$this->channel/$this->version");
    
    $readme=new api\File("$base/$this->channel/$this->version/README.txt");
    
    $readme->put(<<<README
= $pkg / $this->version # $this->channel | READ ME =
README
);
    
    $manifest=new api\File("$base/$this->channel/$this->version/manifest.xml");
    
    $manifest->put(<<<XML
<?xml version="1.0" encoding="utf-8"?>
<manifest app="$this->pkg" version="$this->version" channel="$this->channel">
  <nutshell>
    <![CDATA[$nutshell]]>
  </nutshell>
  <dependencies>
		<dependency type="api" version="$api_version" channel="$api_channel" />
	</dependencies>
	<commands>
	</commands>
</manifest>
XML
);

    $runner=new api\File("$base/$this->channel/$this->version/run.php");
    
    $runner->put(<<<PHP
<?php	
							 					
namespace co2_OS\apps\\$this->pkg\\$this->channel\\v$Version;

use co2_OS as kernel;

class run extends kernel\\run {}
PHP
);

    kernel\aptitude::add(kernel\aptitude::TYPE_APP,$this->pkg,$this->version,$this->channel);
  }
  
  public function __toString()
  
  {
    $ifdev=$this->channel=='dev'?' -d':'';
    
    return "App '$this->pkg/$this->version#$this->channel' successfully generated. Type `co2$ifdev $this->pkg` to begin using";
  }
}
